package org.mixare.gui;

import org.mixare.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Login extends Activity {

	private TextView errMsg;
	private EditText userEdit, passEdit;


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.login);
		errMsg = (TextView) findViewById(R.id.login_error_msg);

		Button login = (Button)findViewById(R.id.login_button);
		login.setOnClickListener( new OnClickListener() {

			public void onClick(View viewParam) {
				userEdit = (EditText) findViewById(R.id.login_edit_username);
				passEdit = (EditText) findViewById(R.id.login_edit_password);

				if(userEdit == null || passEdit == null){
					errMsg.setText(R.string.login_err);
					passEdit.setText("");
				}else{
					String username = userEdit.getText().toString();
					String pass = passEdit.getText().toString();
					try {
						String response = Globals.sendPostRequest("req_id=LOGIN&user="+username+"&pass="+pass);
						int code = Integer.parseInt(response.substring(0, response.indexOf(";")));
						String line = response.substring(response.indexOf(";") + 1);
						if(code == 200) {
							if(line.startsWith("{")){
								errMsg.setText("");
								Intent menu = new Intent(Login.this, MainMenu.class);
								menu.putExtra(Globals.USERNAME, username);
								menu.putExtra(Globals.LEVEL, Globals.getJsonParameter(line, Globals.LEVEL));
								menu.putExtra(Globals.EXP, Globals.getJsonParameter(line, Globals.EXP));
								startActivity(menu);
							}
							else{
								errMsg.setText(line);
								passEdit.setText("");
							}
						}
						else{
							errMsg.setText(R.string.server_err);
						}
					} catch(Exception ex){
						errMsg.setText(R.string.server_err);
					}
				}
			} 
		}); 

		Button register = (Button) findViewById(R.id.login_register_button);
		register.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent reg = new Intent(Login.this, Register.class);
				startActivity(reg);
			}
		});
	}
}